/**
 * Grid Functionality
 */

/**
 * The default row for this data center
 * @return array
 */
function getDefaultRow() {	
	return [ null, jsDateToMySqlDate(new Date()), jsDateToMySqlDate(new Date()), 'new event', '',  '', '1'];
}

/**
 * Adds a new row to the table
 * 
 * @return
 */

function add(addUrl) {
	if (model.canModify()) {
		grid.addRow(getDefaultRow());
		grid.edit.apply();
		refresh();
	} else {
		waitMessage();
	}
}

/**
 * removes the selected row from the store
 * 
 * @return
 */
function remove(deleteUrl) {

	if (grid.selection.selectedIndex == -1) {
		alert("Please select an item first");
		return;
	}
	if(model.canModify()){
		grid.removeSelectedRows();
		refresh();
	}else{
		waitMessage();
	}	
}


// NOTE: supports only default date formatting YYYY-MM-DD HH:MM:SS or YY-MM-DD
// HH:MM:SS
mysqlDateToJsDate = function(inMysqlDateTime, inDateDelim, inTimeDelim) {
	var dt = inMysqlDateTime.split(' '), d = dt[0], t = dt[1], r;
	d = d && d.split(inDateDelim || '-');
	t = t && t.split(inTimeDelim || ':');
	if (d && d.length == 3) {
		r = new Date();
		r.setYear(d[0]);
		r.setMonth(parseInt(d[1]) - 1);
		r.setDate(d[2]);
	}
	if (t && t.length == 3) {
		r = r || new Date();
		r.setHours(t[0]);
		r.setMinutes(t[1]);
		r.setSeconds(t[2]);
	}
	return r || new Date(inMysqlDateTime);
}

jsDateToMySqlDate = function(inDate) {
	var d = new Date(inDate), y = d.getFullYear(), m = dojo.string.pad(d
			.getMonth() + 1), dd = dojo.string.pad(d.getDate())
	return dojo.string.substitute("${0}-${1}-${2}", [ y, m, dd ]);
};

// custom simple MySql date formatter
formatMySqlDate = function(inDatum) {
	return inDatum != dojox.grid.na ? dojo.date.locale.format(
			mysqlDateToJsDate(inDatum), this.constraint) : dojox.grid.na;
}

//custom simple status formatter
formatStatus = function(inDatum) {
	return inDatum == dojox.grid.na ?  dojox.grid.na : getStatusName(inDatum);
}

getStatusName = function (inId) {
	switch (inId) {
	case "1":
		return "completed";
	case "2":
		return "planned";
	case "3":
		return "tentative";
	case "4":
		return "milestone";
	case "5":
		return "release";
	default:
		return "undefined";
	}
}

getStatusId = function (inName) {
	switch (inName) {
	case "completed":
		return "1";
	case "planned":
		return "2";
	case "tentative":
		return "3";
	case "milestone":
		return "4";
	case "release":
		return "5";
	default:
		return "undefined";
	}
}

/**
 * Timeline functionality 
 */

/**
 * 
 * @param now
 * @param refreshUrl
 * @param milestones
 * @return
 */
function setTimeline(now, refreshUrl, milestonesUrl) {

	eventSource = new Timeline.DefaultEventSource(0);
	onLoad = function() {

		var theme = Timeline.ClassicTheme.create();
		theme.event.label.width = 250;
        theme.event.bubble.width = 320;
        theme.event.bubble.height = 220;
        theme.event.highlightColors = ["#FFC000", "#FF0000", "#0000FF"];
        theme.ether.highlightColor = ["#FF111"];

		var bandInfos = [ Timeline.createBandInfo( {
			eventSource :eventSource,
			date :now,
			width :"80%",
			intervalUnit :Timeline.DateTime.WEEK,
			intervalPixels :300,
			theme:          theme
		}), Timeline.createBandInfo( {
			showEventText :false,
			eventSource :eventSource,
			date :now,
			width :"20%",
			intervalUnit :Timeline.DateTime.MONTH,
			intervalPixels :250,
			theme:          theme
		}) ];
		bandInfos[1].syncWith = 0;
		bandInfos[1].highlight = true;
		
		// assign milestones
		if (milestonesUrl != null) {
		
			 dojo.xhrGet( { // 
		        url: milestonesUrl, 
		        handleAs: "text",
		        sync: true,
		        // The LOAD function will be called on a successful response.
		        load: function(response, ioArgs) { 
				 	var milestones = eval(response);
				 	for (var i = 0; i < bandInfos.length; i++) {
					 	var d = new Array(milestones.length);
			        	for (var j = 0; j < milestones.length; j++) {
			        		d[j] =  new Timeline.PointHighlightDecorator({
			                    date:       milestones[j].start,
			                    color:      "#AA0000",
			                    opacity:    30, 
			                    theme:      theme
			                });
			        	}
			        	bandInfos[i].decorators = d;
			        }
					return response; // 
		        	} } );
		}
		
		tl = Timeline.create(document.getElementById("timeline"), bandInfos,
				Timeline.HORIZONTAL);
		tl.loadJSON(refreshUrl, function(json, url) {
			eventSource.loadJSON(json, url);
		});
		
	    setupFilterHighlightControls(document.getElementById("controls"), tl, [0,1], theme);
	};
}

/**
 * 
 */
var resizeTimerID = null;

function onResize() {
	if (resizeTimerID == null) {
		resizeTimerID = window.setTimeout( function() {
			resizeTimerID = null;
			tl.layout();
		}, 500);
	}
}

/**
 * 
 * @return
 */
function getSelectedProject() {
	var list = document.getElementById('projectSelect');
	if (!list || list.value == 'All Projects') {
		return '';
	}
	return "?projectid=" + list.value;
}


function centerTimeline(date) {
    tl.getBand(0).setCenterVisibleDate(Timeline.DateTime.parseGregorianDateTime(date));
}

function setupFilterHighlightControls(div, timeline, bandIndices, theme) {
    var table = document.createElement("table");
    var tr = table.insertRow(0);
    
    var td = tr.insertCell(0);
    td.innerHTML = "Filter:";
    
    td = tr.insertCell(1);
    td.innerHTML = "Highlight:";
    
    var handler = function(elmt, evt, target) {
        onKeyPress(timeline, bandIndices, table);
    };
    
    tr = table.insertRow(1);
    tr.style.verticalAlign = "top";
    
    td = tr.insertCell(0);
    
    var input = document.createElement("input");
    input.type = "text";
    SimileAjax.DOM.registerEvent(input, "keypress", handler);
    td.appendChild(input);
    
    for (var i = 0; i < theme.event.highlightColors.length; i++) {
        td = tr.insertCell(i + 1);
        
        input = document.createElement("input");
        input.type = "text";
        SimileAjax.DOM.registerEvent(input, "keypress", handler);
        td.appendChild(input);
        
        var divColor = document.createElement("div");
        divColor.style.height = "0.5em";
        divColor.style.background = theme.event.highlightColors[i];
        td.appendChild(divColor);
    }
    
    td = tr.insertCell(tr.cells.length);
    var button = document.createElement("button");
    button.innerHTML = "Clear All";
    SimileAjax.DOM.registerEvent(button, "click", function() {
        clearAll(timeline, bandIndices, table);
    });
    td.appendChild(button);
    
    div.appendChild(table);
}

var timerID = null;
function onKeyPress(timeline, bandIndices, table) {
    if (timerID != null) {
        window.clearTimeout(timerID);
    }
    timerID = window.setTimeout(function() {
        performFiltering(timeline, bandIndices, table);
    }, 300);
}
function cleanString(s) {
    return s.replace(/^\s+/, '').replace(/\s+$/, '');
}
function performFiltering(timeline, bandIndices, table) {
    timerID = null;
    
    var tr = table.rows[1];
    var text = cleanString(tr.cells[0].firstChild.value);
    
    var filterMatcher = null;
    if (text.length > 0) {
        var regex = new RegExp(text, "i");
        filterMatcher = function(evt) {
            return regex.test(evt.getText()) || regex.test(evt.getDescription());
        };
    }
    
    var regexes = [];
    var hasHighlights = false;
    for (var x = 1; x < tr.cells.length - 1; x++) {
        var input = tr.cells[x].firstChild;
        var text2 = cleanString(input.value);
        if (text2.length > 0) {
            hasHighlights = true;
            regexes.push(new RegExp(text2, "i"));
        } else {
            regexes.push(null);
        }
    }
    var highlightMatcher = hasHighlights ? function(evt) {
        var text = evt.getText();
        var description = evt.getDescription();
        for (var x = 0; x < regexes.length; x++) {
            var regex = regexes[x];
            if (regex != null && (regex.test(text) || regex.test(description))) {
                return x;
            }
        }
        return -1;
    } : null;
    
    for (var i = 0; i < bandIndices.length; i++) {
        var bandIndex = bandIndices[i];
        timeline.getBand(bandIndex).getEventPainter().setFilterMatcher(filterMatcher);
        timeline.getBand(bandIndex).getEventPainter().setHighlightMatcher(highlightMatcher);
    }
    timeline.paint();
}
function clearAll(timeline, bandIndices, table) {
    var tr = table.rows[1];
    for (var x = 0; x < tr.cells.length - 1; x++) {
        tr.cells[x].firstChild.value = "";
    }
    
    for (var i = 0; i < bandIndices.length; i++) {
        var bandIndex = bandIndices[i];
        timeline.getBand(bandIndex).getEventPainter().setFilterMatcher(null);
        timeline.getBand(bandIndex).getEventPainter().setHighlightMatcher(null);
    }
    timeline.paint();
}


